<template>
  <div class="app-container">
    <el-switch
      v-model="isSwitch"
      active-text="开"
      inactive-text="关"
      @change="switchFun"
      style="width: 100%; margin-bottom: 10px"
    ></el-switch>

    <el-button

      class="filter-item marginRB10"
      type="primary"
      icon="el-icon-plus"
      @click="handleCreate()"
      >添加</el-button
    >
    <el-button

      class="filter-item marginRB10"
      type="primary"
      icon="el-icon-edit"
      @click="handleUpdate()"
      >编辑</el-button
    >
    <!--    <el-button class="marginRB10" type="danger" @click="allDel()" plain>批量删除</el-button>-->

    <el-input
      type="textarea"
      :autosize="{ minRows: 10 }"
      placeholder="..."
      v-model="blacklistText"
      disabled></el-input>

    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="地域名称" prop="regions">
          <el-input
            type="textarea"
            :autosize="{ minRows: 10 }"
            placeholder="多个用逗号隔开，要带上单位：省、市"
            v-model="form.regions"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  saveData,
  deleteData,
  updateData,
  listData,
  switchStatus,
  setSwitch,
  saveRegion,
} from "@/api/config/globalBlackList";
export default {
  data() {
    return {
      listLoading: true,
      isSwitch: false,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10,
      },
      blacklistText: "",
      menuList: [],
      dialogFormVisible: false,
      dialogStatus: "",
      titleMap: {
        update: "编辑",
        create: "增加",
      },
      form: {
        id: undefined,
        regions: undefined,
      },
      rules: {
        regions: [{ required: true, message: "请输入", trigger: "blur" }],
      },
    }
  },
  created() {
    this.getList();
    this.getSwitch();
  },
  methods: {
    getList() {
      this.listLoading = true;
      listData().then(({data}) => {
        this.menuList = data
        this.form.regions = data
        this.listLoading = false
      });
    },
    getSwitch() {
      switchStatus().then((response) => {
        this.isSwitch = response.data.status === "1";
      });
    },
    switchFun() {
      let data = this.isSwitch ? "1" : "2";
      setSwitch({ switch: data }).then((response) => {
        this.getSwitch();
      });
    },
    handleCreate(row) {
      this.resetForm();

      // this.form.regions = this.menuList
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.form = [];
      // this.form.id= row.id
      // this.form.regions= row.regions

      this.form.regions = this.menuList;

      this.dialogStatus = "update";
      this.dialogFormVisible = true;

      this.form = Object.assign({}, this.form);
    },
    handleDelete(row) {
      let data = { ids: row.id };
      deleteData(data).then((response) => {
        if (response.code === 200) {
          this.getList();
          // this.submitOk("删除成功");
          this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
        } else {
          // this.submitFail("删除失败");
          this.$message({
                        message: response.message,
                        type: 'error'
                    });
        }
      });
    },
    allDel() {

      let delNum = [];
      this.$refs.dataList.selection.forEach((k) => {
        delNum.push(k.id);
      });
      if (delNum.length === 0) {
        return;
      }
      let data = { ids: delNum.toString() };
      deleteData(data).then((response) => {
        if (response.code === 200) {
          this.getList();
          // this.submitOk("删除成功");
          this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
        } else {
          // this.submitFail("删除失败");
          this.$message({
                        message: response.message,
                        type: 'error'
                    });
        }
      });
    },
    submitForm() {
      this.form.regions = this.form.regions.replace(/，/g, ",");
      let stringResult = this.form.regions.split(",");
      // stringResult)
      for (let item in stringResult) {
        if (
          stringResult[item].indexOf("省") > -1 &&
          stringResult[item].indexOf("市") > -1
        ) {
          alert("地区不能同时出现省和市");
          return;
        }
      }
      this.$refs["dataForm"].validate((valid) => {
        if (valid && this.dialogStatus === "create") {
          let formData = new FormData();
          for (let item in this.form) {
            this.form[item] === undefined
              ? ""
              : formData.append(item, this.form[item]);
          }
          saveData(formData).then((response) => {
            if (response.code === 200) {
              this.getList();
              // this.submitOk(response.message);
              this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
              this.dialogFormVisible = false;
            } else {
              // this.submitFail(response.message);
              this.$message({
                        message: response.message,
                        type: 'error'
                    });
            }
          });
        } else if (valid && this.dialogStatus === "update") {
          let formData = new FormData();
          for (let item in this.form) {
            this.form[item] === undefined
              ? ""
              : formData.append(item, this.form[item]);
          }
          saveRegion(formData).then((response) => {
            if (response.code === 200) {
              this.getList();
              // this.submitOk(response.message);
              this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
              this.dialogFormVisible = false;
            } else {
              // this.submitFail(response.message);
              this.$message({
                        message: response.message,
                        type: 'error'
                    });
            }
          });
        }
      });
    },
    resetForm() {
      this.form = {
        id: undefined,
        regions: undefined,
      };
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs["dataForm"]) {
        this.$refs["dataForm"].clearValidate(); // 清除整个表单的校验
      }
    },
  },
  watch: {
    menuList: {
      immediate: true,
      handler(value) {
        this.blacklistText = value.join(',')
      }
    }
  }
};
</script>
